package com.lagou.edu.factory;

import com.lagou.edu.annotations.A;
import com.lagou.edu.annotations.S;
import com.lagou.edu.annotations.T;
import com.lagou.edu.config.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 事务动态代理工厂
 */
@S
public class TransactionProxyFactory {

    @A
    private TransactionManager transactionManager;


    public <T> Object getJdkProxy(Object bean){

        if (bean.getClass().isAnnotationPresent(com.lagou.edu.annotations.T.class)){
            Object proxyObject =  Proxy.newProxyInstance(bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(), new InvocationHandler() {

                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object invokeObject = null;
                    try {
                        transactionManager.beginTransaction();
                        invokeObject = method.invoke(bean, args);
                        transactionManager.commit();
                    }catch (Exception e){
                        transactionManager.rollback();
                        throw e;
                    }
                    return invokeObject;
                }
            });
            return proxyObject;
        }
        return bean;
    }

}
